package com.lyc.user.controller;

import com.lyc.user.entity.User;
import com.lyc.user.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author YooLin
 * @Date 2017/7/23 17:40
 * @Description 用户模块
 */
@Controller
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 测试
     * @return 测试页面
     * @throws UnsupportedEncodingException
     * @throws NoSuchAlgorithmException
     */
    @RequestMapping("/test")
    public String test() throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        User user = new User();
//        user.setUsername("root");
//        user.setRealName("YooLin");
//        user.setMobile("18888888888");
//        user.setId(8L);
//        user.setPassword(MD5Util.encryptPassword("root"));
//        userService.addUser(user);
        return "test";
    }

    /**
     * 返回home页面
     * @return 主页面
     */
    @RequestMapping("/home")
    public String home(){
        return "home";
    }

    /**
     * 以json字符串返回当前用户的头像和真实姓名
     * @param session 获取用户信息
     * @return 当前用户的头像和真实姓名
     */
    @RequestMapping("/getUserInfo")
    @ResponseBody
    public User getUserInfo(HttpSession session){
        Object userInfo = session.getAttribute("userInfo");
        if (userInfo instanceof User){
            User user = (User) userInfo;
            user.setPassword(null);
            user.setMobile(null);
            return user;
        }
        return null;
    }

    /**
     * 用户退出
     * @return 返回登录页面
     */
    @RequestMapping("/logout")
    public String logout(){
        //使用shiro退出
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated())
            subject.logout();//退出 在SessionListener监听session销毁，清理权限缓存
        return "login";
    }
}
